<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="changeKeyword" />
        <!-- 树形组件 -->
        <!--
          default-expand-all 默认展开所有节点
          expand-on-click-node="false" 点击节点不展开或收缩, 只要在点击左侧的三角时才展开或收缩
          highlight-current 当前选中节点高亮
         -->
        <el-tree ref="deptTree" :data="depts" :props="defaultProps" default-expand-all :expand-on-click-node="false" highlight-current node-key="id" @current-change="changeNode" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column label="头像" align="center">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" size="small" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column label="入职时间" sortable>
            <template #default="{row}">
              <span>{{ formatDate(row.timeOfEntry) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="assignRole(row.id)">角色</el-button>
              <el-popconfirm
                :title="`确认删除 ${row.username} 吗?`"
                @onConfirm="deleteEmployee(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px;" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height:60px;" type="flex" justify="end" align="middle">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            @current-change="changePage"
          />
        </el-row>
      </div>

      <!-- 导入excel弹层 -->
      <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
      <!-- 分配角色弹层 -->
      <el-dialog title="分配角色" :visible.sync="showRoleDialog" center>
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">
            {{ role.name }}
          </el-checkbox>
        </el-checkbox-group>
        <template #footer>
          <el-button type="primary" size="mini" @click="btnRoleOk">确定</el-button>
          <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetDepartment } from '@/api/department'
import { reqExportEmployee, reqGetEmployee, reqDelEmployee, reqEmployeeDetail, reqAssignRole } from '@/api/employee'
import { reqGetEnabledRole } from '@/api/role'
import { transListToTreeData } from '@/utils'

import dayjs from 'dayjs'
import FileSaver from 'file-saver'

import ImportExcel from './components/ImportExcel.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      // 组织架构数据数组(树形数组)
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 查询员工数据对象
      queryParams: {
        departmentId: null, // 部门的id
        page: 1, // 当前页
        pagesize: 10, // 每页条数
        keyword: '' // 查询关键字
      },
      // 总条数
      total: 0,
      // 表格数据数组
      list: [],
      // 控制导入excel弹层的显示/隐藏
      showExcelDialog: false,
      // 控制分配角色弹层的显示/隐藏
      showRoleDialog: false,
      // 所有可用的角色数组
      roleList: [],
      // 选中角色的id数组
      roleIds: [],
      // 当前操作的员工id,
      currentEmployeeId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 1. 获取组织部门数据
    async getDepartment() {
      // 1.1 转化部门数据
      const res = await reqGetDepartment()
      this.depts = transListToTreeData(res, 0)

      // 1.2 获取首个节点的id并记录
      this.queryParams.departmentId = this.depts[0].id
      // 1.3 选中节点
      // console.log(this.$refs.roleTree)
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })

      // 1.4 首次加载员工列表
      this.getEmployeeList()
    },
    // 2. 点击切换选中节点
    changeNode(row) {
      // 2.1 记录选中节点对应的部门id
      this.queryParams.departmentId = row.id
      // 2.3 把当前页设置为第一页
      this.queryParams.page = 1
      // 2.2 获取员工列表
      this.getEmployeeList()
    },
    // 3. 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await reqGetEmployee(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 4. 格式化日期
    formatDate(str) {
      return dayjs(str).format('YYYY年MM月DD日')
    },
    // 5. 切换当前页
    changePage(newpage) {
      this.queryParams.page = newpage
      this.getEmployeeList()
    },
    // 6. 实现模糊搜索
    changeKeyword() {
      // 防抖处理: 单位时间内执行最后一次
      clearTimeout(this.timerId)
      this.timerId = setTimeout(() => {
        // 6.1 设置页面为第一页
        this.queryParams.page = 1
        // 6.2 查询员工
        this.getEmployeeList()
      }, 300)
    },
    // 7. 批量导出员工
    async exportExcel() {
      const blob = await reqExportEmployee()
      // console.log(res)
      // FileSaver.saveAs(blob对象, '文件名称.xlsx')
      FileSaver.saveAs(blob, '员工信息表.xlsx')
    },
    // 8. 删除员工
    async deleteEmployee(id) {
      // 8.1 调用删除员工的接口函数
      await reqDelEmployee(id)
      // 8.2 判断当前页是否只有一条数据 && 当前页 > 1
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      // 8.3 提示用户 并 重新加载
      this.$message({
        type: 'success',
        message: '删除员工成功'
      })
      this.getEmployeeList()
    },
    // 9. 打开分配权限的弹层
    async  assignRole(id) {
      // 9.2 获取所有可用角色
      this.roleList = await reqGetEnabledRole()
      // 9.3 获取当前用户拥有的所有角色
      const { roleIds } = await reqEmployeeDetail(id)
      this.roleIds = roleIds
      // 9.1 展示分配角色弹层
      this.showRoleDialog = true
      // 9.4 记录当前操作员工的id
      this.currentEmployeeId = id
    },

    // assignRole(id) {
    //   // 9.2 获取所有可用角色
    //   // this.roleList =  reqGetEnabledRole()
    //   // 9.3 获取当前用户拥有的所有角色
    //   // const { roleIds } =  reqEmployeeDetail(id)

    //   Promise.all([reqGetEnabledRole(), reqEmployeeDetail(id)]).then(([res1, res2]) => {
    //     this.roleIds = res2.roleIds
    //     // 9.1 展示分配角色弹层
    //     this.showRoleDialog = true
    //     // 9.4 记录当前操作员工的id
    //     this.currentEmployeeId = id
    //   })
    // },
    // 10. 点击分配角色按钮
    async btnRoleOk() {
      await reqAssignRole({ id: this.currentEmployeeId, roleIds: this.roleIds })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
